package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.utils.common.AppJwtUtil;
import com.heima.common.excpetion.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;

@Service("ApUserLoginService")
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {

        //判断入参的合法性
        if (dto.getEquipmentId() == null) {
            // 再判断用户是否传入账户密码 都没有 直接返回
            if (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword()))
                CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }


        {
            //用户使用的是临时登录
            if (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword())) {

                HashMap<String, Object> hashMap = new HashMap<>();
                //使用设备号生成Token返回
                hashMap.put("token", AppJwtUtil.getToken(Long.valueOf(dto.getEquipmentId())));
                return ResponseResult.okResult(hashMap);
            }
            //用户使用的是账号密码登录

            //根据账号查询用户信息
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

            //用户不存在
            if (apUser == null)
                CustException.cust(AppHttpCodeEnum.LOGIN_NOTFOUND_ERROR);

            //判断用户密码是否正确
            String inPutPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());

            //账号密码错误
            if (!inPutPassword.equals(apUser.getPassword()))
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

            //账号密码正确 返回Token
            HashMap<String, Object> hashMap = new HashMap<>();
            // 脱敏
            apUser.setPassword(null);
            apUser.setSalt(null);
            hashMap.put("token", AppJwtUtil.getToken(Long.valueOf(apUser.getId())));
            hashMap.put("apUser", apUser);
            return ResponseResult.okResult(hashMap);
        }

    }
}
